package com.example.lock.zkLock;

import com.example.lock.DistributedLock;

import java.util.concurrent.TimeUnit;

public class SimpleZookeeperLock extends BaseZookeeperLock implements
        DistributedLock {

    //锁名称前缀,成功创建的顺序节点如lock-0000000000,lock-0000000001,...
    private static final String LOCK_NAME = "lock-";

    // zookeeper中locker节点的路径
    private final String basePath;

    // 获取锁以后自己创建的那个顺序节点的路径
    private String ourLockPath;

    private boolean internalLock(long time, TimeUnit unit) throws Exception {
        ourLockPath = attemptLock(time, unit);
        return ourLockPath != null;

    }

    public SimpleZookeeperLock(ZkClientExt client, String basePath){
        super(client,basePath,LOCK_NAME);
        this.basePath = basePath;

    }


    public String acquireLock(String lockName, Long acquireTime, Long expireTime) throws Exception {
        if ( !internalLock(-1, null) ) {
            //throw new IOException("连接丢失!在路径:'"+basePath+"'下不能获取锁!");
            return null;
        }
        return null;
    }


    public String acquireLock(String lockName, Long time, TimeUnit unit) throws Exception {
         internalLock(time, unit);
         return null;
    }


    public void release(String lockName, String identify) throws Exception {
        releaseLock(ourLockPath);
    }

    public Boolean extendLockTime(String lockName, Long time, String identify) {
        return true;
    }
}
